/**
 * 主应用程序
 * 初始化相册和时间轴，配置Flickity
 */

class AlbumApp {
    constructor() {
        this.processor = null;
        this.generator = null;
        this.mainCarousel = null;
        this.timelineCarousel = null;
        this.config = window.config || {};
        this.isInitialized = false;
        this.currentYear = null;

        // 状态锁，避免时间轴和主相册双向触发造成“回滚/追加”
        this.isUserNavigatingTimeline = false;
        this.isMainNavigating = false;
        this.pendingTimelineSync = null;
        // 微节流：合并主相册连续变化下的时间轴同步
        this.timelineImmediateYear = null;
        this.timelineImmediateTimer = null;
        this.timelineImmediateDelay = typeof this.config.timelineImmediateDelay === 'number'
            ? this.config.timelineImmediateDelay
            : 0;
        // 时间轴点击后主相册同步的极短延迟
        this.timelineClickSyncDelay = typeof this.config.timelineClickSyncDelay === 'number'
            ? this.config.timelineClickSyncDelay
            : 0;
        this.hasPendingTimelineClickMainSync = false;

        // 交互状态
        this.isDraggingMain = false;
        this.isMouseFollowActive = false;
        this.hoveredIndex = null;

        // 交互/动画参数（可由 window.config.effects 覆盖）
        const defaultEffects = {
            selectedScale: 1,
            selectedTranslateZ: 0,
            adjacentRotateY: 8,
            adjacentTranslateZ: 0,
            adjacentTranslateY: 0,
            adjacentScale: 1,
            pushNear: 20,
            pushFar: 35,
            followMaxDeg: 3,
            followInTransition: '80ms ease-out',
            followOutTransition: '200ms ease',
            tiltTransition: '300ms ease'
        };
        this.effects = Object.assign({}, defaultEffects, (this.config && this.config.effects) || {});

        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            this.showLoading();

            // 检查依赖
            if (!this.checkDependencies()) {
                throw new Error('缺少必要的依赖');
            }

            // 初始化数据处理器
            this.processor = new AlbumDataProcessor(window.albumData);

            // 验证数据
            const validation = this.processor.validateData();
            if (!validation.isValid) {
                throw new Error('数据验证失败: ' + validation.errors.join(', '));
            }

            // 初始化生成器
            this.generator = new AlbumGenerator(this.processor, this.config);

            // 渲染HTML结构（包含隐藏代理导航）
            this.generator.renderAlbumWithProxy();

            // 等待DOM更新
            await this.waitForDOM();

            // 初始化Flickity
            this.initFlickity();

            // 设置事件监听
            this.setupEventListeners();

            // 设置初始状态
            this.setInitialState();

            this.hideLoading();
            this.isInitialized = true;

            console.log('相册初始化完成', this.generator.getRenderStats());

        } catch (error) {
            console.error('初始化失败:', error);
            this.showError(error.message);
        }
    }

    /**
     * 检查依赖
     */
    checkDependencies() {
        const required = ['Flickity', 'AlbumDataProcessor', 'AlbumGenerator'];
        const missing = required.filter(dep => !window[dep]);

        if (missing.length > 0) {
            console.error('缺少依赖:', missing);
            return false;
        }

        return true;
    }

    /**
     * 等待DOM更新
     */
    waitForDOM() {
        return new Promise(resolve => {
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', resolve);
            } else {
                setTimeout(resolve, 100);
            }
        });
    }

    /**
     * 初始化Flickity轮播
     */
    initFlickity() {
        // 顺序：先主相册 -> 再隐藏代理（asNavFor 主相册）-> 最后可见时间轴
        this.initMainCarousel();
        this.initProxyCarousel();
        this.initTimelineCarousel();
        this.setupCarouselSync();
    }

    /**
     * 初始化主相册
     */
    initMainCarousel() {
        const container = document.getElementById('main-carousel');
        if (!container) {
            throw new Error('找不到主相册容器');
        }

        // 主相册配置 - 基于原版Swiper配置转换
        const mainOptions = {
            // 基础配置
            cellSelector: '.main-carousel-cell',
            wrapAround: true, // 对应 loop: true

            // 居中配置 - 对应 centeredSlides: true
            cellAlign: 'center',
            contain: false,
            percentPosition: false, // 使用像素定位以匹配原版

            // 懒加载配置：一次加载6张，避免生成时依赖图片宽度
            lazyLoad: 6,

            // UI配置
            prevNextButtons: true,
            pageDots: false,

            // 初始索引
            initialIndex: this.getInitialIndex(),

            // 动画配置 - 对应 speed: 800
            selectedAttraction: 0.025,
            friction: 0.28,

            // 拖拽配置
            draggable: false,
            dragThreshold: 3,

            // 自适应高度
            adaptiveHeight: false,
            setGallerySize: true,

            // 图片加载
            imagesLoaded: true,

            // 可访问性
            accessibility: true,

            // 禁用分组单元格，使用selectCell方法实现年份联动
            groupCells: false,

            // 自由滚动模式
            freeScroll: false,

            // Hash导航 - 启用hash功能改善联动
            hash: true
        };



        this.mainCarousel = new Flickity(container, mainOptions);

        // 拖拽状态标记，避免拖拽中触发跟随动画
        this.mainCarousel.on('dragStart', () => { this.isDraggingMain = true; });
        this.mainCarousel.on('dragEnd',   () => { this.isDraggingMain = false; });

        // 绑定事件 - asNavFor会自动处理联动
        this.mainCarousel.on('change', this.onMainCarouselChange.bind(this));
        this.mainCarousel.on('settle', this.onMainCarouselSettle.bind(this));
        // 首次渲染完成后就应用一次3D效果，避免初始状态没有倾斜
        this.mainCarousel.on('ready', () => this.apply3DEffectToAdjacentSlides());
        this.mainCarousel.on('lazyLoad', this.onImageLazyLoad.bind(this));
        this.mainCarousel.on('bgLazyLoad', this.onImageLazyLoad.bind(this));
    }

    /**
     * 初始化时间轴轮播 - 完全按照原版Swiper配置
     */
    initTimelineCarousel() {
        const container = document.getElementById('timeline-nav');
        if (!container) {
            throw new Error('找不到时间轴容器');
        }

        // 时间轴配置（可见年份导航） - 不直接 asNavFor
        const timelineOptions = {
            cellSelector: '.timeline-cell',
            wrapAround: true,
            cellAlign: 'center',
            contain: false,
            prevNextButtons: false,
            pageDots: false,
            initialIndex: this.getTimelineInitialIndex(),
            draggable: true,
            freeScroll: false,
            groupCells: false,
            accessibility: true,
            percentPosition: false,
            selectedAttraction: 0.04,
            friction: 0.35,
            imagesLoaded: false,
            adaptiveHeight: false,
            setGallerySize: false
        };

        this.timelineCarousel = new Flickity(container, timelineOptions);
        // 记录时间轴年份顺序，供主相册联动索引映射
        this.timelineYears = this.timelineCarousel.cells.map(c => parseInt(c.element.getAttribute('data-year'), 10));




        // 拖动开始：标记来自时间轴的用户交互
        this.timelineCarousel.on('dragStart', () => {
            this.isUserNavigatingTimeline = true;
        });

        // 点击年份：先让时间轴自己平滑滚动到该cell，联动在 settle 里统一处理
        this.timelineCarousel.on('staticClick', (_evt, _pointer, cellElement, cellIndex) => {
            if (cellIndex == null) return;
            this.isUserNavigatingTimeline = true;

            // 点击年份淡入动画：点击的年份淡入，原来的年份立刻消失
            this.animateTimelineClick(cellElement, cellIndex);

            this.timelineCarousel.select(cellIndex, true, false);
        });



        // 停止后（无论点击或拖动），再联动主相册，避免 wrapAround 内部重排造成“回滚/追加”视觉
        this.timelineCarousel.on('settle', this.onTimelineSettle.bind(this));

        // 不绑定任何事件，完全使用asNavFor联动
    }

    /**
     * 时间轴点击动画：点击的年份淡入，原来的年份立刻消失
     */
    animateTimelineClick(clickedElement, clickedIndex) {
        if (!this.timelineCarousel) return;

        // 获取当前激活的年份元素
        const currentSelected = this.timelineCarousel.element.querySelector('.timeline-cell.is-selected');

        // 如果点击的就是当前激活的，不需要动画
        if (currentSelected && currentSelected === clickedElement) return;

        // 立刻移除当前激活年份的选中状态和透明度
        if (currentSelected) {
            currentSelected.classList.remove('is-selected');
            currentSelected.style.opacity = '1';
        }

        // 为点击的年份添加淡入动画
        if (clickedElement) {
            clickedElement.style.opacity = '0.3';
            clickedElement.classList.add('is-selected');

            // 使用 requestAnimationFrame 确保样式应用后再开始动画
            requestAnimationFrame(() => {
                clickedElement.style.transition = 'opacity 0.3s ease';
                clickedElement.style.opacity = '1';
            });
        }
    }

    /**
     * 初始化隐藏代理导航（与主相册 1:1），并用 asNavFor 绑定主相册
     */
    initProxyCarousel() {
        const proxyContainer = document.getElementById('timeline-proxy');
        if (!proxyContainer) return;

        // 生成代理导航内容（若为空）
        if (!proxyContainer.children.length) {
            this.generator.renderProxyNav('timeline-proxy');
        }

        const proxyOptions = {
            cellSelector: '.proxy-cell',
            asNavFor: this.mainCarousel ? this.mainCarousel.element : '#main-carousel',
            wrapAround: true,
            cellAlign: 'center',
            contain: false,
            prevNextButtons: false,
            pageDots: false,
            draggable: true,
            freeScroll: false,
            accessibility: false,
            setGallerySize: false,
        };

        this.proxyCarousel = new Flickity(proxyContainer, proxyOptions);

        // 可见年份时间轴的点击仅使用 Flickity 的 staticClick 处理，避免原生 click 冲突
    }


    /**
     * 设置轮播同步
     */
    setupCarouselSync() {
        // 方案2：不再重建时间轴。保持可见时间轴独立，
        // 隐藏代理导航通过 asNavFor 与主相册联动。
        return;
    }


    /**
     * 主相册变化事件 - 只记录状态，不手动同步
     */
    onMainCarouselChange(index) {
        // 使用事件提供的 index 来确定年份，避免 selectedElement 时序问题
        const year = this.processor.getYearByIndex(index);
        if (year == null) return;
        this.currentYear = String(year);
        console.log('主相册变化:', index, this.currentYear);
        // 动画开始（select/change）即刻应用3D倾斜效果
        this.apply3DEffectToAdjacentSlides();

        // 主相册由按钮/拖动引发变更时，直接让时间轴同步（确保不会跳过中间节点）
        if (this.timelineCarousel && !this.isUserNavigatingTimeline) {
            const yearStr = this.currentYear;

            const performTimelineSync = () => {
                this.timelineImmediateTimer = null;
                const targetYear = this.timelineImmediateYear;
                // 直接通过 DOM 找到对应年份 cell → 反查索引，最稳妥
                const cellEl = document.querySelector(`#timeline-nav .timeline-cell[data-year="${targetYear}"]`);
                if (cellEl) {
                    const to = this.timelineCarousel.cells.findIndex(c => c.element === cellEl);
                    if (to >= 0) {
                        this.timelineCarousel.select(to, true, false);
                        this.pendingTimelineSync = null;
                        return;
                    }
                }
                // 兜底：尝试按预计算的年份数组匹配并立即联动
                if (this.timelineYears && this.timelineYears.length) {
                    const to = this.timelineYears.findIndex(y => String(y) === targetYear);
                    if (to >= 0) {
                        this.timelineCarousel.select(to, true, false);
                        this.pendingTimelineSync = null;
                        return;
                    }
                }
            };

            // 微节流：合并极短时间内的多次变化
            this.timelineImmediateYear = yearStr;
            if (this.timelineImmediateTimer) {
                clearTimeout(this.timelineImmediateTimer);
                this.timelineImmediateTimer = null;
            }

            if (this.timelineImmediateDelay <= 0) {
                performTimelineSync();
            } else {
                this.timelineImmediateTimer = setTimeout(performTimelineSync, this.timelineImmediateDelay);
            }
            return;
        }
        // 若无法定位索引，记录待同步的年份，由 settle 阶段统一处理
        this.pendingTimelineSync = String(year);
    }

    /**
     * 主相册停止事件
     */
    onMainCarouselSettle(index) {
        // 轮播停止，统一执行一次时间轴同步，避免 change 阶段与 wrapAround 内部重排冲突
        console.log('主相册停止在索引:', index);
        if ((typeof this.pendingTimelineSync === 'string' || typeof this.pendingTimelineSync === 'number') && this.timelineCarousel) {
            const yearStr = String(this.pendingTimelineSync);
            this.pendingTimelineSync = null;
            if (this.isUserNavigatingTimeline) {
                return;
            }
            // 直接通过 DOM 找到对应年份 cell，再反查 cells 中的索引，最稳妥
            const cellEl = document.querySelector(`#timeline-nav .timeline-cell[data-year="${yearStr}"]`);
            if (cellEl) {
                const to = this.timelineCarousel.cells.findIndex(c => c.element === cellEl);
                if (to >= 0) {
                    this.timelineCarousel.select(to, true, false);
                    return;
                }
            }
            // 兜底：尝试按预计算的年份数组匹配
            if (this.timelineYears && this.timelineYears.length) {
                const to = this.timelineYears.findIndex(y => String(y) === yearStr);
                if (to >= 0) this.timelineCarousel.select(to, true, false);
            }
        }

        // 滑动动画结束后，为相邻图片添加3D倾斜效果
        this.apply3DEffectToAdjacentSlides();
    }
    /**
     * 为主相册的前一张与后一张应用3D倾斜效果
     */
    apply3DEffectToAdjacentSlides() {
        if (!this.mainCarousel) return;
        const selectedCell = this.mainCarousel.selectedElement;
        if (!selectedCell) return;
        // 若正在进行鼠标跟随，不在此阶段覆盖其变换
        if (this.isMouseFollowActive) return;

        // 仅清除每个cell内部.image-container上的内联transform，避免覆盖Flickity对cell的transform
        const cells = this.mainCarousel.cells.map(c => c.element);
        cells.forEach(cellEl => {
            const inner = cellEl.querySelector('.image-container');
            if (inner) {
                inner.style.transform = 'scale(1) rotateY(0)';
                inner.style.transformOrigin = 'bottom center';
                inner.style.transition = `transform ${this.effects.tiltTransition}`;
            }
        });

        // 获取相邻元素（支持wrapAround）
        const selectedIndex = this.mainCarousel.selectedIndex;
        const total = this.mainCarousel.cells.length;
        const prevIndex = (selectedIndex - 1 + total) % total;
        const nextIndex = (selectedIndex + 1) % total;
        const prevCell = this.mainCarousel.cells[prevIndex]?.element;
        const nextCell = this.mainCarousel.cells[nextIndex]?.element;

        // 应用3D倾斜到内部容器：围绕底边旋转，保持底部对齐
        const angle = this.effects.adjacentRotateY;
        const scale = this.effects.adjacentScale;
        if (prevCell) {
            const inner = prevCell.querySelector('.image-container');
            if (inner) {
                inner.style.transform = `scale(${scale}) rotateY(${angle}deg)`;
                inner.style.transformOrigin = 'bottom center';
                inner.style.transition = `transform ${this.effects.tiltTransition}`;
            }
        }
        if (nextCell) {
            const inner = nextCell.querySelector('.image-container');
            if (inner) {
                inner.style.transform = `scale(${scale}) rotateY(-${angle}deg)`;
                inner.style.transformOrigin = 'bottom center';
                inner.style.transition = `transform ${this.effects.tiltTransition}`;
            }
        }

        // 选中项内部容器归正
        const selectedInner = selectedCell.querySelector('.image-container');
        if (selectedInner) {
            selectedInner.style.transform = `translateZ(0) rotateY(0) scale(${this.effects.selectedScale}) translateZ(${this.effects.selectedTranslateZ}px)`;
            selectedInner.style.transition = `transform ${this.effects.tiltTransition}`;
        }
    }



    /**
     * 时间轴停止事件
     */
    onTimelineSettle(index) {
        // 时间轴停止：若本次来自用户交互（点击/拖动），统一联动主相册到该年份的第一张
        console.log('时间轴停止在索引:', index);
        this.updateTimelineActiveState();
        if (!this.isUserNavigatingTimeline) return;
        this.isUserNavigatingTimeline = false;

        if (!this.timelineCarousel || !this.mainCarousel) return;
        const yearCell = this.timelineCarousel.selectedElement;
        if (!yearCell) return;
        const year = yearCell.getAttribute('data-year');
        const firstIndex = this.processor.getIndexByYear(year);
        if (typeof firstIndex === 'number' && firstIndex >= 0) {
            // 极短延迟合并：避免与 Flickity 当前帧的内部重排冲突
            if (this._timelineClickTimer) {
                clearTimeout(this._timelineClickTimer);
                this._timelineClickTimer = null;
            }
            const triggerMainSelect = () => {
                this.hasPendingTimelineClickMainSync = false;
                this._timelineClickTimer = null;
                this.mainCarousel.select(firstIndex, true, false);
            };

            if (this.timelineClickSyncDelay <= 0) {
                triggerMainSelect();
            } else {
                this.hasPendingTimelineClickMainSync = true;
                this._timelineClickTimer = setTimeout(triggerMainSelect, this.timelineClickSyncDelay);
            }
        }
    }



    /**
     * 图片懒加载事件
     */
    onImageLazyLoad(event, cellElement) {
        console.log('图片加载完成:', cellElement);

        // 移除加载占位符
        const placeholder = cellElement.querySelector('.loading-placeholder');
        if (placeholder) {
            placeholder.style.opacity = '0';
        }
    }

    /**
     * 导航到指定年份 - 使用选择器字符串
     */
    navigateToYear(year) {
        const index = this.processor.getIndexByYear(year);

        // 尝试使用选择器字符串导航
        const targetSlide = document.querySelector(`#slide-${index}`);
        if (targetSlide && this.mainCarousel) {
            this.mainCarousel.selectCell(targetSlide, false, false);
        } else {
            // 回退到索引方式
            this.navigateToIndex(index);
        }
    }

    /**
     * 导航到指定索引
     */
    navigateToIndex(index) {
        if (this.mainCarousel && index >= 0) {
            this.mainCarousel.select(index);
        }
    }

    /**
     * 更新时间轴选择状态
     */
    updateTimelineSelection(year) {
        // 移除所有选中状态
        const timelineCells = document.querySelectorAll('.timeline-cell');
        timelineCells.forEach(cell => {
            cell.classList.remove('is-nav-selected');
        });

        // 添加当前年份的选中状态
        const currentCell = document.querySelector(`.timeline-cell[data-year="${year}"]`);
        if (currentCell) {
            currentCell.classList.add('is-nav-selected');
        }
    }

    /**
     * 更新时间轴激活状态 - 使用Flickity的is-selected类
     */
    updateTimelineActiveState() {
        if (!this.timelineCarousel) return;

        // Flickity会自动添加is-selected类到激活的cell
        // 我们只需要确保样式正确应用
        const selectedCell = this.timelineCarousel.selectedElement;
        if (selectedCell) {
            const year = selectedCell.dataset.year;
            console.log('时间轴激活年份:', year);
        }
    }

    /**
     * 根据主相册索引获取年份
     */
    getYearByMainIndex(index) {
        return this.processor.getYearByIndex(index);
    }

    /**
     * 获取初始索引
     */
    getInitialIndex() {
        const minYear = this.processor.getMinYear();
        return minYear ? this.processor.getIndexByYear(minYear) : 0;
    }

    /**
     * 获取时间轴初始索引
     */
    getTimelineInitialIndex() {
        const minYear = this.processor.getMinYear();
        const timelineYears = this.processor.getTimelineData();
        const index = timelineYears.indexOf(minYear);
        return index >= 0 ? index : 0;
    }

    /**
     * 设置初始状态
     */
    setInitialState() {
        const initialYear = this.processor.getMinYear();
        if (initialYear) {
            this.currentYear = initialYear;
            this.updateTimelineSelection(initialYear);
        }
    }

    /**
     * 检查是否为移动设备
     */
    isMobile() {
        return window.innerWidth <= (this.config.mobileBreakpoint || 768);
    }

    /**
     * 获取分组单元格配置 - 模拟Swiper的slidesPerView
     */
    getGroupCells() {
        const width = window.innerWidth;

        // 对应原版Swiper的breakpoints配置
        if (width <= 320) {
            return 1; // 320px以下显示1张
        } else if (width <= 960) {
            return 1; // 320-960px显示1张
        } else {
            return '26%'; // 960px以上显示2.6张的效果
        }
    }

    /**
     * 获取按年份分组的配置 - 用于与时间轴联动
     */
    getYearGroupCells() {
        // 使用实际图片数据计算年份分组
        const allImages = this.processor.getAllImages();
        const yearCounts = {};

        // 统计每个年份的图片数量
        allImages.forEach(image => {
            if (!yearCounts[image.year]) {
                yearCounts[image.year] = 0;
            }
            yearCounts[image.year]++;
        });

        // 按年份排序，返回每个年份的图片数量
        const sortedYears = Object.keys(yearCounts).sort();
        const groupSizes = sortedYears.map(year => yearCounts[year]);

        console.log('年份分组配置:', {
            years: sortedYears,
            counts: groupSizes,
            total: groupSizes.reduce((sum, count) => sum + count, 0)
        });

        return groupSizes;
    }

    /**
     * 设置事件监听
     */
    setupEventListeners() {
        // 文档级鼠标移动：仅对当前选中 slide 的内部容器做 3D 跟随
        document.addEventListener('mousemove', (e) => {
            if (!this.mainCarousel) return;
            if (this.isDraggingMain) return;

            const activeEl = this.mainCarousel.selectedElement;
            if (!activeEl) return;
            const inner = activeEl.querySelector('.image-container');
            if (!inner) return;

            const rect = activeEl.getBoundingClientRect();
            const inSlide = e.clientX >= rect.left && e.clientX <= rect.right &&
                            e.clientY >= rect.top && e.clientY <= rect.bottom;

            if (inSlide) {
                this.isMouseFollowActive = true;
                const cx = rect.left + rect.width / 2;
                const cy = rect.top + rect.height / 2;
                const offsetX = (e.clientX - cx) / (rect.width / 2);
                const offsetY = (e.clientY - cy) / (rect.height / 2);
                const rotateY = offsetX * this.effects.followMaxDeg;
                const rotateX = -offsetY * this.effects.followMaxDeg;
                inner.style.transition = `transform ${this.effects.followInTransition}`;
                const base = `translateZ(${this.effects.selectedTranslateZ}px) scale(${this.effects.selectedScale})`;
                inner.style.transform = `${base} rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
                inner.style.willChange = 'transform';
            } else if (this.isMouseFollowActive) {
                this.isMouseFollowActive = false;
                inner.style.transition = `transform ${this.effects.followOutTransition}`;
                inner.style.transform = '';
            }
        });

        // Hover 推开效果：在 cell 上 mouseenter/leave 时给相邻单元加位移类
        this.mainCarousel.on('staticClick', (_evt, _pointer, cellEl, cellIndex) => {
            if (cellIndex == null) return;
            this.mainCarousel.select(cellIndex);
        });

        // 由于 Flickity 不会代理 hover，我们直接在容器上事件委托
        const containerEl = document.getElementById('main-carousel');
        if (containerEl) {
            containerEl.addEventListener('mouseover', (ev) => {
                const cell = ev.target.closest('.main-carousel-cell');
                if (!cell || !containerEl.contains(cell)) return;
                const all = this.mainCarousel.cells.map(c => c.element);
                const idx = all.indexOf(cell);
                if (idx < 0 || this.hoveredIndex === idx) return;

                // 先清理上一次 hover 残留：恢复内联transform并移除类
                all.forEach(el => {
                    el.classList.remove('push-left','push-right','push-left-far','push-right-far');
                    const inner = el.querySelector('.image-container');
                    if (inner && inner.dataset.baseTransform != null) {
                        inner.style.transform = inner.dataset.baseTransform;
                        delete inner.dataset.baseTransform;
                    }
                });

                const setPush = (target, delta) => {
                    if (!target) return;
                    const inner = target.querySelector('.image-container');
                    if (!inner) return;
                    if (inner.dataset.baseTransform == null) {
                        inner.dataset.baseTransform = inner.style.transform || '';
                    }
                    inner.style.transform = `translateX(${delta}px) ${inner.dataset.baseTransform}`.trim();
                };

                const prev = all[(idx - 1 + all.length) % all.length];
                const next = all[(idx + 1) % all.length];
                const prevPrev = all[(idx - 2 + all.length) % all.length];
                const nextNext = all[(idx + 2) % all.length];

                prev && prev.classList.add('push-left');
                next && next.classList.add('push-right');
                prevPrev && prevPrev.classList.add('push-left-far');
                nextNext && nextNext.classList.add('push-right-far');

                setPush(prev, -20);
                setPush(next, 20);
                setPush(prevPrev, -35);
                setPush(nextNext, 35);

                this.hoveredIndex = idx;
            }, true);

            containerEl.addEventListener('mouseleave', () => {
                const all = this.mainCarousel ? this.mainCarousel.cells.map(c => c.element) : [];
                all.forEach(el => {
                    el.classList.remove('push-left','push-right','push-left-far','push-right-far');
                    const inner = el.querySelector('.image-container');
                    if (inner && inner.dataset.baseTransform != null) {
                        inner.style.transform = inner.dataset.baseTransform;
                        delete inner.dataset.baseTransform;
                    }
                });
                this.hoveredIndex = null;
            }, true);
        }

        // 窗口大小变化
        window.addEventListener('resize', this.debounce(this.onResize.bind(this), 250));

        // 键盘导航
        document.addEventListener('keydown', this.onKeyDown.bind(this));

        // 图片错误处理
        document.addEventListener('error', this.onImageError.bind(this), true);
    }

    /**
     * 窗口大小变化处理
     */
    onResize() {
        if (this.mainCarousel) {
            this.mainCarousel.resize();
        }
        if (this.timelineCarousel) {
            this.timelineCarousel.resize();
        }
    }

    /**
     * 键盘事件处理
     */
    onKeyDown(event) {
        if (!this.isInitialized) return;

        switch (event.key) {
            case 'ArrowLeft':
                event.preventDefault();
                this.mainCarousel.previous();
                break;
            case 'ArrowRight':
                event.preventDefault();
                this.mainCarousel.next();
                break;
            case 'Home':
                event.preventDefault();
                this.navigateToIndex(0);
                break;
            case 'End':
                event.preventDefault();
                this.navigateToIndex(this.processor.getAllImages().length - 1);
                break;
        }
    }

    /**
     * 图片错误处理
     */
    onImageError(event) {
        if (event.target.tagName === 'IMG') {
            event.target.src = this.config.fallbackImage;
            console.warn('图片加载失败，使用备用图片:', event.target.dataset.flickityLazyload);
        }
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const loading = document.getElementById('loading-indicator');
        if (loading) {
            loading.style.display = 'flex';
        }
    }

    /**
     * 隐藏加载状态
     */
    hideLoading() {
        const loading = document.getElementById('loading-indicator');
        if (loading) {
            loading.style.display = 'none';
        }
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        this.hideLoading();
        const error = document.getElementById('error-message');
        if (error) {
            error.querySelector('p').textContent = message;
            error.style.display = 'block';
        }
    }

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 销毁应用
     */
    destroy() {
        if (this.mainCarousel) {
            this.mainCarousel.destroy();
        }
        if (this.timelineCarousel) {
            this.timelineCarousel.destroy();
        }

        // 移除事件监听
        window.removeEventListener('resize', this.onResize);
        document.removeEventListener('keydown', this.onKeyDown);
        document.removeEventListener('error', this.onImageError);

        this.isInitialized = false;
    }

    /**
     * 获取应用状态
     */
    getState() {
        return {
            isInitialized: this.isInitialized,
            currentYear: this.currentYear,
            currentIndex: this.mainCarousel ? this.mainCarousel.selectedIndex : -1,
            stats: this.generator ? this.generator.getRenderStats() : null
        };
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.albumApp = new AlbumApp();
});

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AlbumApp;
} else {
    // 浏览器环境下，将类添加到全局作用域
    window.AlbumApp = AlbumApp;
}
